package edu.gdkm.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

/**
 * 代替springMVC配置文件：
 * 1、扫描组件  2、视图解析器  3、view-controller  4、default-servlet-handler   5、mvc注解驱动
 * 6、文件上传解析器   7、异常处理    8、拦截器
 */
@Configuration
//1、扫描组件
@ComponentScan("edu.gdkm.controller")
//5、mvc注解驱动
@EnableWebMvc
public class SpringMvcConfig implements WebMvcConfigurer {
    //使用默认的servlet处理静态资源
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
    //Spring3.0后提供静态资源访问路径配置
    //mapping：映射
    //location：本地资源路径，注意必须是webapp根目录下的路径。
    //两个*，它表示映射静态资源目录下所有的URL，包括子路径（即接多个/）
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/images/**").addResourceLocations("/images/");
        registry.addResourceHandler("/js/**").addResourceLocations("/js/");
        registry.addResourceHandler("/css/**").addResourceLocations("/css/");
        registry.addResourceHandler("/page/**").addResourceLocations("/page/");
    }

    //配置拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
//        FirstInterceptor firstInterceptor = new FirstInterceptor();
////        这种方式会拦截所有请求
////        registry.addInterceptor(firstInterceptor);
//        registry.addInterceptor(firstInterceptor).addPathPatterns("/**") //拦截所有
//                .excludePathPatterns("/index", "/login", "error");      //但是这些不拦截
////        registry.addInterceptor(new SecondInterceptor());
    }


    //配置视图控制 view-controller
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/register").setViewName("register");
    }


    /**
     * 配置请求视图映射
     * @return
     */
    @Bean
    public InternalResourceViewResolver resourceViewResolver()
    {
        InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
        //请求视图文件的前缀地址
        internalResourceViewResolver.setPrefix("/WEB-INF/jsp/");
        //请求视图文件的后缀
        internalResourceViewResolver.setSuffix(".jsp");
        return internalResourceViewResolver;
    }

    /**
     * 视图配置
     * @param registry
     */
    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
//        registry.viewResolver(resourceViewResolver());
        registry.jsp("/WEB-INF/jsp/",".jsp");

    }




}
